package com.chixing.day20.day20_Home;

import java.io.*;
import java.math.BigDecimal;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class TransRecordManger{


    // 声明成员变量用于存储所有的交易记录数据
    private List<TransRecord> records = new ArrayList<>();


    public void load(InputStream in) throws IOException {
        // 将获取的字节流转换为字符流并包装成缓冲流
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = br.readLine()) != null) {
            // 排除注释行（以"#"开头）
            if (!line.startsWith("#")) {
                TransRecord record = parseDateToObj(line);
                records.add(record);
            }
        }
    }

    // 将一行文本数据解析为一个交易记录对
    private TransRecord parseDateToObj(String line) {
        TransRecord tr = new TransRecord();
        String[] data = line.split("\\|");
        tr.setCustNum(data[0]);
        tr.setCustName(data[1]);
        tr.setJobNum(data[2]);
        tr.setGender(Objects.equals(data[3], "1") ? "男" : "女");
        tr.setUserName(data[4]);
        tr.setCash(new BigDecimal(data[6]));
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime time = LocalDateTime.parse(data[5],formatter);
        tr.setCreatTime(time);
        return tr;
    }

    // 加载数据
    public void load(String fileName) throws IOException {
        File f = new File(fileName);
        InputStream is = new FileInputStream(f);
        load(is);
    }

    //取所有记录

    public List<TransRecord> getAll() {
        return records;
    }

    //按客户号查询记录
   public List<TransRecord> findcust (String cust){
        return records.stream().filter(r -> Objects.equals(r.getCustNum(),cust)).collect(Collectors.toList());
   }

   //按日期段查询记录
    public List<TransRecord> findByDate (String startTime , String endTime){

        return null;
    }

    //取得总金额
    public BigDecimal total(){
        BigDecimal result = new BigDecimal(0);
        for(TransRecord tr: records){
            BigDecimal cash = tr.getCash();
            result = result.add(cash);
        }
        return result;
    }
    }

